<template>
  <el-row v-if="currEmailSession" :class="tabType + '_conbox'">
    <el-col :span="16">
      <div class="chat_msg_box">
        <!--邮件会话框头部-->
        <div class="chat_head" v-show="tabType === 'email_todo'">
          <el-row>
            <el-col :span="24">
              <div class="chat_top">
                <!--会话名称-->
                <div class="chat_top_head clearBoth">
                  <div class="title">
                    <div class="email_title_con" :title="(emailCustData.name?emailCustData.name:$t('public.unknowLocationCustomer')) + '  ' + currEmailSession.createTime">
                      {{emailCustData.name?emailCustData.name:$t('public.unknowLocationCustomer')}}
                    <span class="chat_title_time">{{currEmailSession.createTime}}</span></div>
                  </div>
                </div>
                <!--转接座席-->
                <el-popover ref="popover1" placement="bottom" width="220" trigger="click" v-model.trim="chatHead.popover1Visible">
                  <div class="popover1">
                    <input type="text" :placeholder="$t('public.pleaseEnter')" class="popover1_input" v-model.trim="popover1Search" v-on:keyup="searchTree1"/>
                    <!--<input type="text" :placeholder="$t('public.pleaseEnter')" class="popover1_inpit" v-model.trim="popover1Search" v-on:keyup="searchTree1"/>-->
                    <ul class="tree">
                      <li class="quickReSys transfer_li clearBoth ellipsis" v-for="(model, index) in chatHead.onlineAgents" @click.stop="transferAgent(model._id, model.displayName)" :key="model._id">
                        <span class="cata-name ellipsis" >{{model.displayName}}</span>
                      </li>
                    </ul>
                  </div>
                </el-popover>
                <!--邮件标记-->
                <el-popover ref="popover2" placement="bottom" width="88" trigger="click" class="mail_pop" v-model.trim="chatHead.popover2Visible">
                  <div class="popover2 popover_email">
                    <ul class="email_mark_ul">
                      <li class="email_unread email_mark_li"><el-checkbox v-model.trim="chatHead.readStateChecked"  @change="switchReadState(chatHead.readStateChecked,'switchReadState')">{{$t('email.unReadEmail')}}</el-checkbox></li>
                      <li class="email_mark_li"><el-checkbox v-model.trim="chatHead.starStateChecked"  @change="switchStarState(chatHead.starStateChecked, 'starStateChecked')">{{$t('email.starEmail')}}</el-checkbox></li>
                    </ul>
                      </li>
                    </ul>
                  </div>
                </el-popover>
                <!--邮件归类-->
                <el-popover ref="popover3" placement="bottom" width="88" trigger="click" class="mail_pop" v-model.trim="chatHead.popover3Visible">
                  <div class="popover3 popover_email">
                    <ul class="email_category_ul">
                      <li class="email_category_li" v-for="category in chatHead.mailCategories" @click.stop="selectCategory(category, 'selectCategory')">{{category.categoryName}}</li>
                    </ul>
                  </div>
                </el-popover>
                <!--结束会话框-->
                <end-session-box v-if="chatHead.dialogTableVisible" :info="chatHead" @endSession="endSessionFun" @changeEndSiFlag="changeEndSessionFlag"></end-session-box>
                <!--功能按钮-->
                <div class="chat_transfer" >
                  <el-button type="text" class="email_mark" v-popover:popover3 size="mini" @click="initCategoryData" ><span class="">{{checkedCategory}}</span><span class="el-icon-arrow-down"></span></el-button>
                  <el-button type="text" class="email_mark" v-popover:popover2 size="mini" @click="initMarkData" ><span>{{$t('email.emailMark')}}</span><span class="el-icon-arrow-down"></span> </el-button>
                  <el-tooltip class="item" effect="dark" transition="" :content="$t('email.mailTransfer')" placement="top">
                    <el-button type="text" class="iconfont icon-zhuanjie1" v-popover:popover1 size="mini" @click="showRedirectPopup" ></el-button>
                  </el-tooltip>
                  <el-tooltip class="item" effect="dark" transition="" :content="$t('public.finish')" placement="top">
                    <el-button type="text" class="iconfont icon-wancheng1" @click="showFinishPopup" size="mini"></el-button>
                  </el-tooltip>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
        <!--邮件消息历史-->
        <div class="chat_msg_con">
          <el-row>
            <el-col :span="24">
              <div class="email_chat_msg chatMsgCon" :class="chatMsgCon.font">
                <div class="email_msg_inner">
                  <div v-if="currSessionHistory" v-for="(chatMsg, index) in currSessionHistory" class="clearBoth" :class="chatMsg.emailType === 'system' ? 'system_li' : ''" :key="chatMsg._id">
                    <!--收到消息-->
                    <div class="chat_item in clearBoth msg_li" v-if="chatMsg.emailType === 'receive'">
                      <div class="chat_user_info">
                        <customer-avatar
                          :size="20"
                          class="client_msg"
                          :status="emailCustData.status"
                        ></customer-avatar>
                        <div class="chat_time">{{getChatShortTime(chatMsg)}}</div>
                      </div>
                      <div class="chat_content">
                        <div class="chat_content_arrow"></div>
                        <p v-html="chatMsg.contentText"></p>
                        <div class="clearBoth email_do_btn_box">
                          <div class="email_do_btn clearBoth">
                            <span v-if="tabType === 'email_todo'" class="replyAll" @click="replyAll(chatMsg)">{{$t('email.replayAll')}}</span>
                            <div v-if="chatMsg.attachment.length>0" class="attachment_box clearBoth">
                              <!-- 邮件附件详情 -->
                              <span class="iconfont icon-fujian attachment_btn" @click.stop="showChatAttach(chatMsg.attachment, index)">
                                <span>({{chatMsg.attachment.length}})</span>
                              </span>
                              <div class="popover_attachment" v-if="chatMsgCon.currAttachment === index && chatMsgCon.currAttachVisible">
                                <div class="pop_arrow"></div>
                                <ul>
                                  <li v-for="attach in chatMsgCon.chatAttach" class="ellipsis">
                                    <a :href="common.addAttname(attach)" @click.stop="chatMsgCon.currAttachVisible=false" :download="attach.name" :title="attach.name" target="_blank">{{attach.name}}</a>
                                  </li>
                                </ul>
                              </div>
                            </div>
                            <div class="el-icon-arrow-right iconfont icon-youjianxiangqing"  @click.stop="showEmailDetails(chatMsg)"></div>
                          </div>
                        </div>
                      </div>
                    </div>
                    <!--回复消息-->
                    <div class="chat_item out clearBoth msg_li"  v-if="chatMsg.emailType === 'reply' || chatMsg.emailType === 'initiative'">
                      <div class="chat_content">
                        <div class="chat_content_arrow_out"></div>
                        <div class="send_status failure iconfont icon-tishi" v-if="chatMsg.status === 'fail'"></div>
                        <div class="send_status success iconfont icon-fasongchenggong" v-if="chatMsg.status === 'success'"></div>
                        <div class="send_status process" v-if="!chatMsg.status"></div>
                        <p v-html="chatMsg.contentText"></p>
                        <div class="clearBoth email_do_btn_box">
                          <div class="email_do_btn clearBoth">
                            <div v-if="chatMsg.attachment.length>0" class="attachment_box clearBoth">
                              <!-- 邮件附件详情 -->
                              <div class="iconfont icon-fujian attachment_btn" @click.stop="showChatAttach(chatMsg.attachment, index)">
                                <span>({{chatMsg.attachment.length}})</span>
                              </div>
                              <div class="popover_attachment" v-if="chatMsgCon.currAttachment === index && chatMsgCon.currAttachVisible">
                                <div class="pop_arrow"></div>
                                <ul>
                                  <li v-for="attach in chatMsgCon.chatAttach" class="ellipsis">
                                    <a :href="common.addAttname(attach)" @click.stop="chatMsgCon.currAttachVisible=false" :download="attach.name" :title="attach.name" target="_blank">{{attach.name}}</a>
                                  </li>
                                </ul>
                              </div>
                            </div>
                            <div class="el-icon-arrow-right iconfont icon-youjianxiangqing" @click.stop="showEmailDetails(chatMsg)"></div>
                          </div>
                        </div>
                      </div>
                      <div class="chat_user_info_out clearBoth">
                        <div class="chat_user_img" >
                          <img v-if="im_icon(chatMsg)" :src="im_icon(chatMsg)" alt=""/>
                        </div>
                        <div class="chat_time">{{getChatShortTime(chatMsg)}}</div>
                      </div>
                    </div>
                  </div>
                  <!-- 详情对话框 -->
                  <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="5vh" :title="$t('email.emailDetail')" id="email_detail" :visible.sync="chatMsgCon.showDetail">
                    <email-details :lastEmail="mailDetailInfo" :chatMsgCon="chatMsgCon" :chatMsg="chatMsgCon.emailType" :currEmailSession="currEmailSession"></email-details>
                    <div class="tableVisibleBtnBox clearBoth">
                      <el-button class="tableVisibleBtn" @click.stop="chatMsgCon.showDetail = false" size="small">{{$t('public.cancel')}}</el-button>
                    </div>
                  </el-dialog>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
        <!--拖动条-->
        <div class="resizeBar" v-if="tabType === 'email_todo'" id="resizeBar"></div>
        <!--发送邮件编辑器-->
        <div class="send_chat_msg email_send_box" v-show="tabType === 'email_todo'">
          <el-row>
            <el-col :span="24">
              <!-- 邮件聊天框部分 -->
              <el-form class="send_msg_form email_send_msg_box">
                <div class="attach_and_copy_box">
                  <div class="copy_box_p box_p" v-if="inboxEmail.toBoxShow">
                    <span class="cancel_copy">{{$t('email.recipient')}}:</span>
                    <EmailSearch :size="'small'" :placeholder="$t('email.editRecipient')" :inputData="toGroup" :dataArray="autoAssociationArray" @inputChange="toInputChange" @initData="initDataChange"></EmailSearch>
                    <!--<input-tag :inputData="inboxEmail.toGroup" :validate="'Email'" @inputChange="toInputChange" :placeholder="$t('email.editRecipient')"></input-tag>-->
                    <i class="iconfont icon-guanbi" @click.stop="cancelToInput"></i>
                  </div>
                  <div class="copy_box_p box_p" v-if="inboxEmail.copyBoxShow">
                    <span class="cancel_copy">{{$t('email.copyFor')}}:</span>
                    <EmailSearch :size="'small'" :placeholder="$t('email.addCopy')" :inputData="ccGroup" @inputChange="ccInputChange" @initData="initDataChange"></EmailSearch>
                    <!--<input-tag :inputData="inboxEmail.ccGroup" :validate="'Email'" @inputChange="ccInputChange" :placeholder="$t('email.editCopy')"></input-tag>-->
                    <i class="iconfont icon-guanbi" @click.stop="cancelCcInput"></i>
                  </div>
                  <div class="attach_box_p box_p" v-if="(inboxEmail.attachGroup.length>0 || attachUpPro.flag )">
                    <attach-input-tag :inputData="inboxEmail.attachGroup" :uploadProgress="attachUpPro" @inputChange="attachInputChange" ></attach-input-tag>
                  </div>
                </div>
                <!--<div class="quill">-->
                  <!--<quill-editor ref="myTextEditor"-->
                                <!--v-model.trim="inboxEmail.content"-->
                                <!--:config="inboxEmail.editorOption">-->
                  <!--</quill-editor>-->
                <!--</div>-->
                <div id="email_editor_menu" class="unknown-question padding-top"></div>
                <div id="email_editor_content" class="unknown-question padding-top"></div>
                <el-form-item class="footer_box clearBoth">
                  <div class="attach_and_copy">
                    <div id="uploadEmailFile" :class="(inboxEmail.attachGroup.length>0 && !inboxEmail.copyBoxShow) ? 'click' : '' " @click.stop="changeCopyBoxShow()" class="addAttach" >
                      <span class="iconfont icon-fujian"></span>
                      {{$t('email.addAttach')}}
                      <span v-if="inboxEmail.attachGroup.length>0">({{inboxEmail.attachGroup.length}})</span>
                    </div>
                    <div class="addCopy" :class="inboxEmail.copyBoxShow===true?'click':''"  @click.stop="changeCopyBoxShow(true)">{{$t('email.addCopy')}}<span v-if="inboxEmail.ccGroup.length>0">({{inboxEmail.ccGroup.length}})</span></div>
                  </div>
                  <el-button type="primary" class="replyMsg primary_btn" @click.stop="replyEmailInbox" size="small">{{$t('email.send')}}</el-button>
                  <span class="incidentalAgentInfo">
                    <el-checkbox v-model.trim="inboxEmail.carryAgentInfo">{{$t('email.incidentalAgentInfo')}}</el-checkbox>
                  </span>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-col>

    <!--右侧详情 -->
    <el-col :span="8">
      <div class="chat_info_box email_chat_info">
        <div class="chat_info">
          <!-- 处理中 -->
          <el-tabs class="chat_info_todo" v-show="tabType === 'email_todo'" :active-name="activeName" @tab-click="tabChange">
            <el-tab-pane :label="$t('webchat.auxiliaryInformation')" class="basic_info chat_detailed_info_box" name="otherInfo">
              <h3 class="chat_info_title" :title="currEmailSession.subject">{{currEmailSession.subject}}</h3>
              <!--客户-->
              <div class="chat_info_li clearBoth" >
                <span class="chat_info_li_title">{{$t('public.customer')}}:<b v-if="currEmailSession.from" class="chat_info_li_con">{{currEmailSession.from.addr}}</b></span>
                <!--<b v-if="currEmailSession.from.addr" class="chat_info_li_con">{{currEmailSession.from.addr}}</b>-->
              </div>
              <!--评价-->
              <div class="chat_info_li clearBoth investigate_box" >
                <span class="chat_info_li_title">{{$t('email.satisfiedEvaluate')}}:</span>
                <span class="chat_info_li_con" @mouseenter="investigateShow(true)">{{currEmailSession.satisfaction}}</span>
                <ul v-show="investigate" class="investigate_con clearBoth" @mouseleave="investigateShow()" @mouseenter="investigateShow(true)">
                  <li class="clearBoth">
                    <i>{{$t('email.satisfiedEvaluate')}}：</i>
                    <span>{{currEmailSession.satisfaction}}</span>
                  </li>
                  <li class="clearBoth">
                    <i>{{$t('email.evalutionLabel')}}：</i>
                    <span v-show="currEmailSession.label && currEmailSession.label.length > 0">
                      <b v-for="item in currEmailSession.label">{{item}}</b>
                    </span>
                  </li>
                  <li class="clearBoth">
                    <i>{{$t('email.evalutionContent')}}：</i>
                    <span class="investigate_content">{{currEmailSession.proposal}}</span>
                  </li>
                </ul>
              </div>
              <!--备注-->
              <div class="chat_info_remark chat_info_li">
                <span class="chat_info_li_title">{{$t('public.remark')}}</span>
                <textarea class="chat_info_li_remarks" rows="3" :placeholder="$t('public.pleaseEnter')" v-on:blur="editRemark($event)">{{currEmailSession.remark}}</textarea>
              </div>
            </el-tab-pane>

            <!-- 快捷回复-->
            <el-tab-pane :label="$t('email.commonWords')" class="basic_info quick_replay_box" name="quickreply">
              <div class="quickreplay_box">
                <!--系统快捷回复-->
                <div class="quickreplay_sys">
                  <div class="quickBoxTit">
                    {{$t('webchat.systemCommon')}}
                  </div>
                  <ul class="tree" v-if="sysQuickReply.length">
                    <li class="quickReSys quickReSysIndex" v-for="(model, index) in sysQuickReply" :key="model._id">
                      <div class="cursor_li sys_quick_li" @click.stop="itemToggle(index)" :index="index" :title="model.name">
                        <span class="sys_quick_li_span"><i :class="open.index===index && open.isOn ? 'el-icon-minus' : 'el-icon-plus'"></i></span>
                        <div class="cata-name ellipsis sys_quick_li_title">{{model.name}}</div>
                      </div>
                      <ul v-show="open.index === index && open.isOn === true" v-if="model.children && model.children.length" class="quick_re_sys_ul">
                        <li class="quickReSys quickReLi ellipsis" v-for="item in model.children">
                          <span class="cata-name ellipsis">{{item.content}}</span>
                          <span class="quickReBox clearBoth">
                         <el-tooltip class="item" effect="dark" transition="" :content="$t('public.paste')" placement="top">
                          <i class="quickRe iconfont icon-fuzhi" @click.stop="quickCopyMsg(item.content)"></i>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" transition="" :content="$t('webchat.send')" placement="top">
                          <i class="quickRe iconfont icon-fasong" @click.stop="quickSendMsg(item.content)"></i>
                        </el-tooltip>
                        </span>
                        </li>
                      </ul>
                    </li>
                  </ul>
                </div>

                <!-- 自定义快捷回复-->
                <div class="quickreplay_custome_title">
                  {{$t('webchat.customize')}}
                  <el-tooltip class="item" effect="dark" transition="" :content="$t('public.edit2')" placement="top">
                    <span class="edit_img iconfont icon-beizhu" @click.stop="showQuickReplyEditInput" v-show="custQuickReplyEditIsShow === true"></span>
                  </el-tooltip>
                </div>
                <div class="quickreplay_custom">
                  <ul class="quickreplay_custom_con" v-show="custQuickReplyEditIsShow" @mouseleave="mouseleaveCustom">
                    <li class="quickReLi ellipsis" v-for="(item, index) in customQuickReply.rdata">
                      <span>{{item.value}}</span>
                      <span class="quickReBox clearBoth">
                         <el-tooltip class="item" effect="dark" transition="" :content="$t('public.paste')" placement="top">
                          <i class="quickRe iconfont icon-fuzhi" @click.stop="quickCopyMsg(item.value)"></i>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" transition="" :content="$t('webchat.send')" placement="top">
                          <i class="quickRe iconfont icon-fasong" @click.stop="quickSendMsg(item.value)"></i>
                        </el-tooltip>
                      </span>
                    </li>
                  </ul>
                </div>
                <!--编辑自定义快捷回复-->
                <div class="quickreplay_custom_edit" v-show="custQuickReplyEditIsShow === false">
                    <el-form :model="editCustomQuickReply" ref="editCustomQuickReply" class="demo-dynamic">
                      <el-button type="text" @click.stop="addQuickReplyItem" size="small" class="color el-icon-plus"></el-button>
                      <el-form-item v-for="(domain, index) in editCustomQuickReply.rdata" class="quickreplay_li" :prop="'rdata.' + index + '.value'" :rules="{required: true, message: $t('email.quickReplayNotEmpty'), trigger: 'blur'}">
                        <input type="text" class="quickreplay_custom_edit_input" v-model.trim="domain.value"/>
                        <el-button class="edit_del el-icon-minus color" type="text" size="mini" @click.prevent="removeQuickReplyItem(domain)"></el-button>
                      </el-form-item>
                        <div class="button_box">
                          <el-button @click.stop="custQuickReplySubmit()" class="primary_btn" size="small">{{$t('public.cancel')}}</el-button>
                          <el-button @click.stop="custQuickReplySubmit(true)" class="primary_btn" type="primary" size="small">{{$t('public.save')}}</el-button>
                        </div>
                    </el-form>
                  </div>
              </div>
            </el-tab-pane>
          </el-tabs>
          <!-- 全部 -->
          <div v-show="tabType === 'email_all'" class="chat_info_all">
            <h3 class="chat_info_title">{{currEmailSession.subject}}</h3>
            <!--客户-->
            <div class="chat_info_li clearBoth" >
              <span class="chat_info_li_title">{{$t('public.customer')}}:</span>
              <span v-if="currEmailSession.from" class="chat_info_li_con">{{customerAddr}}</span>
            </div>
            <!--所属企业客服邮箱-->
            <div class="chat_info_li clearBoth" >
              <span class="chat_info_li_title">{{$t('email.serviceEmail')}}:</span>
              <span v-if="currEmailSession.to" class="chat_info_li_con">{{serviceEmail}}</span>
            </div>
            <!--来往邮件数-->
            <div class="chat_info_li clearBoth" >
              <span class="chat_info_li_title">{{$t('email.emailCount')}}:</span>
              <span v-if="currEmailSession.totalEmailNum" class="chat_info_li_con">{{currEmailSession.totalEmailNum}}</span>
            </div>
            <!--结束类型-->
            <div class="chat_info_li clearBoth" >
              <span class="chat_info_li_title">{{$t('email.endType')}}:</span>
              <span class="chat_info_li_con">{{finishReason}}</span>
            </div>
            <!--评价-->
            <div class="chat_info_li clearBoth investigate_box" >
              <span class="chat_info_li_title">{{$t('email.satisfiedEvaluate')}}:</span>
              <span class="chat_info_li_con" @mouseenter="investigateShow(true)">{{currEmailSession.satisfaction}}</span>
              <ul v-show="investigate" class="investigate_con clearBoth" @mouseleave="investigateShow()" @mouseenter="investigateShow(true)">
                <li class="clearBoth">
                  <i>{{$t('email.satisfiedEvaluate')}}：</i>
                  <span>{{currEmailSession.satisfaction}}</span>
                </li>
                <li class="clearBoth">
                  <i>{{$t('email.evalutionLabel')}}：</i>
                  <span v-show="currEmailSession.label && currEmailSession.label.length > 0">
                    <b v-for="item in currEmailSession.label">{{item}}</b>
                  </span>
                </li>
                <li class="clearBoth">
                  <i>{{$t('email.evalutionContent')}}：</i>
                  <span class="investigate_content">{{currEmailSession.proposal}}</span>
                </li>
              </ul>
            </div>
            <!--创建时间-->
            <div class="chat_info_li clearBoth email_createtime" >
              <span class="chat_info_li_title">{{$t('public.createTime')}}:</span>
              <span v-if="currEmailSession.createTime" class="chat_info_li_con">{{currEmailSession.createTime}}</span>
            </div>
            <!--座席首次回复时间-->
            <div class="chat_info_li clearBoth" >
              <span class="chat_info_li_title">{{$t('email.agentFirstReplyTime')}}:</span>
              <span v-if="currEmailSession.firstReplyTime" class="chat_info_li_con">{{currEmailSession.firstReplyTime}}</span>
            </div>
            <!--完成时间-->
            <div class="chat_info_li clearBoth" >
              <span class="chat_info_li_title">{{$t('email.endTime')}}:</span>
              <span v-if="currEmailSession.endTime" class="chat_info_li_con">{{currEmailSession.endTime}}</span>
            </div>
            <!--持续时长-->
            <div class="chat_info_li clearBoth" >
              <span class="chat_info_li_title">{{$t('email.durationTime')}}:</span>
              <span v-if="currEmailSession.endTime" class="chat_info_li_con">{{getTimeLength(currEmailSession.lastEmailTimestamp , currEmailSession.createTimeStamp)}}</span>
            </div>
            <!--备注-->
            <div class="chat_info_remark">
              <span class="chat_info_li_title">{{$t('public.remark')}}:</span>
              <textarea class="chat_info_li_remarks" rows="3" :placeholder="$t('public.pleaseEnter')" v-on:blur="editRemark($event)">{{currEmailSession.remark}}</textarea>
            </div>
          </div>
        </div>
      </div>
    </el-col>
  </el-row>
</template>
<script type="text/javascript">
  import CustomerAvatar from '@/components/ui-modules/customer-avatar/CustomerAvatar'
  import { deepClone, formatTimestamp, getCache, m7Language, filterXSS } from '@/utils/m7Utils'
  import * as types from '@/store/modules/email/mutation-types.js'
  import { isEmpty } from 'lodash'
  import InputTag from '@/components/public-modules/input/InputTag'
  import EmailSearch from '@/components/public-modules/email-search'
  import AttachInputTag from './AttachInputTag'
  import EndSessionBox from '@/components/public-modules/ImEndSessionBox/EndSessionBox'
  import {uploadTo7moorEmailDomain} from '@/utils/qiniuUtils'
  import EmailAttachment from './EmailAttachment'
  import * as uuid from 'uuid'
  import { common } from '@/utils/cosUrl'
  import emailDetails from './emailDetails.vue'
  import Editor from 'wangeditor'

  export default {
    name: 'EmailContainer',
    props: {
      refresh: {
        type: String,
        default: ''
      },
      refreshRight: Number
    },
    data () {
      return {
        common,
        tabType: 'email_todo',
        chatHead: {     // 会话框头部数据
          mailCategories: [],   // 邮件分类
          onlineAgents: [],   // 当前在线坐席
          isActiveOne: '999',
          isActiveTwo: '999',
          isActiveThree: '999',
          defaultProps: {
            children: 'children',
            label: 'label'
          },
          dialogTableVisible: false,
          endOptionsUl: [],   // 结束会话类别
          majorstwo: [],
          majorsthree: [],
          endSessionActive: [],   // 选中的结束会话类别
          endSessionFlag: false,
          readStateChecked: false,
          starStateChecked: false,
          popover1Visible: false,
          popover2Visible: false,
          popover3Visible: false,
          endSessionLength: 0
        },
        chatMsgCon: {
          show: true,
          font: 'font12',
//          chatMsgs: [],
          emailDetail: {  //
            to: [],
            cc: [],
            attachment: []
          },
//          attachGroup: [],
          forwardGroup: [],
//          attachment: [],
          showDetail: false,
          showDetailAttach: false,
          showForward: false,
          chatAttach: [],
          currAttachment: '',
          currAttachVisible: false
        },
        custQuickReplyEditIsShow: true,
        editCustomQuickReply: {},
        oldCustomQuickReply: {},
        inboxEmail: {
          content: '',
          dialogVisible: false,
          editorOption: {
            placeholder: '',
            modules: {
              toolbar: [
                ['bold', 'italic', 'underline', 'strike', {'list': 'ordered'}, {'list': 'bullet'}, {'header': [1, 2, 3, 4, 5, 6, false]}, {'color': []}, {'background': []}, {'font': []}, {'align': []}, 'link', 'emailUpLoadFile', 'clean']
              ]
            }
          },
          ccGroup: [],
          toGroup: [],
          attachGroup: [],
          copyBoxShow: false,
          toBoxShow: false,
          carryAgentInfo: true
        },
        attachUpPro: {
          flag: false,
          progress: ''
        },
        activeName: 'otherInfo',
        chatInfoVal: {
          chatInfo: []
        },
        open: {
          index: -1,
          isOn: false
        },
        showSuggest: false,
        loading: true,
        popover1Search: '',
        popoLoading: false,
        pop1Clone: {},
        pop2Clone: {},
        openPop1: {
          index: -1,
          isOn: false
        },
        options5: [],
        forwardAddr: [],
        remarkClone: '',
        editor: {},
        modelShowFlag: false,
        modelShow: {
          content: ''
        },
        modelShowCustomerFlag: false,
        modelShowCustomer: {
          content: ''
        },
        autoAssociationArray: [],
        investigate: false,
        toGroup: [],
        ccGroup: [],
        m7uploaders: [],
        resizeParams: { // 拖动改变邮件框的大小
          flag: false,
          moveLen: 0
        }
      }
    },
    computed: {
      checkedCategory () {
        let current = this.$t('email.emailCategory')
        if (!this.$store.state.email.current.email_todo.currentSession.category) {
          return current
        }
//        let mailCategories = this.$store.state.session.dicMap.mailCategorys
        let mailCategories = this.$getCache('mailCategorys')
        for (let i in mailCategories) {
          if (mailCategories[i]._id === this.$store.state.email.current.email_todo.currentSession.category) {
            current = mailCategories[i].categoryName
            break
          }
        }
        return current
      },
      customerAddr () {
        if (this.currEmailSession.initiative) {
          let addr = ''
          try {
            this.currEmailSession.to.forEach((item) => {
              addr += item.addr + ', '
            })
            addr = addr.substring(0, addr.length - 2)
          } catch (e) {}
          return addr
        } else {
          return this.currEmailSession.from.addr
        }
      },
      serviceEmail () {
        if (this.currEmailSession.initiative) {
          return this.currEmailSession.from.addr
        } else {
          return this.currEmailSession.to.addr
        }
      },
      finishReason () {
        if (this.currEmailSession.initiative) {
          return '系统结束'
        } else if (this.currEmailSession.finishReason) {
          return this.currEmailSession.finishReason
        } else {
          return ''
        }
      },
      sysQuickReply () {
        let arr = this.$store.getters.getSysQuickReplyForEmail || []
        let arrNew = deepClone(arr)
        return arrNew
      },
      customQuickReply () {
        return this.$store.getters.getCustomQuickReplyForEmail
      },
      agentName () {
        let data = ''
        if (this.$store.getters.agents[this.currEmailSession.agent]) {
          data = this.$store.getters.agents[this.currEmailSession.agent].displayName
        }
        return data
      },
      currEmailSession () {
        if (this.tabType) {
          let session = this.$store.state.email.current[this.tabType].currentSession
          this.remarkClone = session.remark || ''
          return session
        } else {
          return {}
        }
      },
      currSessionHistory () {
        return this.tabType ? this.$store.state.email.current[this.tabType].currentSessionHistory : []
      },
      emailCustData () {
        return this.tabType ? this.$store.state.email.current[this.tabType].currentCustomer : {}
      },
      mailDetailInfo () {
        return this.chatMsgCon.emailDetail
      },
      emailContent () {
        let content = deepClone(this.mailDetailInfo.content) || ''
        let newData = content.replace(/<style[^>]*?>[\s\S]*?<\/style>/g, '')
        return newData
      },
      sessionUserId () {
        return this.$store.state.session.user._id
      },
      attachmentMaxSize () {
        return this.$store.state.attachmentMaxSize
      }
    },
    watch: {
      // 如果路由有变化，会再次执行该方法
      $route (to, form) {
        if (to.path.split('/')[2] === 'email') {
          this.fetchData()
        }
      }
//      'inboxEmail.copyBoxShow': 'chatMsgChange'
    },
    created () {
      this.fetchData()
    },
    components: {
      CustomerAvatar,
      InputTag,
      EmailSearch,
      AttachInputTag,
      EmailAttachment,
      EndSessionBox,
      emailDetails
    },
    methods: {
      mouseenter1 (data, index, index2) {
        this.modelShowFlag = true
        this.modelShow.content = data.content
        let box = document.getElementsByClassName('quickReBoxShow')[0]
        let top = 24 + 22 + 22 * index + 22 * index2
        box.style.cssText = 'top: ' + top + 'px'
      },
      mouseleave (data, index) {
        this.modelShowFlag = false
        this.modelShow.content = ''
      },
      mouseleaveCustom (data, index) {
        this.modelShowCustomerFlag = false
        this.modelShowCustomer.content = ''
      },
      fetchData () {
        let path = this.$route.path.split('/')
        this.tabType = path[3]
        this.sessionId = path[4]
      },
      initEmailRelate () {
        this.$store.dispatch('emailConfigEnter', {}).then((res) => {
          this.supportEmails = res.data.emailRelate
        })
      },
      searchTree1 () {
        let str = this.popover1Search
        let dataLi = []
        if (str) {
          this.pop1Clone.forEach((item) => {
            let liName = item.displayName
            if (liName.indexOf(str) !== -1) {
              dataLi.push(item)
            }
          })
          this.chatHead.onlineAgents = dataLi
        } else {
          this.chatHead.onlineAgents = this.pop1Clone
        }
      },
      // 邮件聊天框相关
      replyEmailInbox () {
        let content = this.editor.txt.html().replace('<p>', '').replace('</p>', '').replace('<br>', '')
        if (new RegExp('<table border="0" width="100%" cellpadding="0" cellspacing="0">').test(content)) {
          content = content.replace(/<table border="0" width="100%" cellpadding="0" cellspacing="0">/g, '<table style="width:100%;" cellpadding="2" cellspacing="0" border="1" bordercolor="#262626">')
        }
        let text = this.editor.txt.text()
        if (!text.trim()) {
          let str = this.editor.txt.html()
          text = str.replace(/<[^>]+>/g, '')
        }
        if (!content && !text) {
          this.$message({message: this.$t('email.isNullByContent'), type: 'warning'})
          return false
        }
        let ccGroup = []
        let toGroup = []
        if (this.inboxEmail.toGroup.length) {
          toGroup = this.inboxEmail.toGroup
        } else {
          toGroup.push(this.currEmailSession.from)
        }
        this.inboxEmail.ccGroup.forEach((item, index) => {
          ccGroup.push(item.addr)
        })
        let data = {
          sessionId: this.currEmailSession._id,
          shortId: this.currEmailSession.shortId,
          to: toGroup,
          from: this.currEmailSession.to,
          subject: this.currEmailSession.subject,
          supportEmail: this.currEmailSession.supportEmail,
          attachment: this.inboxEmail.attachGroup,
          cc: ccGroup || [],
          content: content,
          contentText: text,
          carryAgentInfo: this.inboxEmail.carryAgentInfo,
          displayName: this.agentName,
          firstReplyTime: this.currEmailSession.firstReplyTime,
          agentFirstReplyTime: this.currEmailSession.agentFirstReplyTime,
          lastMailId: this.$store.state.email.current[this.tabType].lastMailId
        }
        replyEmailInboxDispatch(this.$store, data).then((res) => {
          this.$nextTick(function () {
            if (document.getElementsByClassName('email_chat_msg').length) {
              document.getElementsByClassName('email_chat_msg')[0].scrollTop = document.getElementsByClassName('email_msg_inner')[0].scrollHeight
            }
            if (!this.currEmailSession.agentFirstReplyTime && !this.currEmailSession.firstReplyTime) {
              this.$store.commit(types.UPDATE_EMAIL_FIRST_REPLY, res.data)
            }
          })
        })
        this.editor.txt.html('')
        this.inboxEmail.ccGroup = []
        this.inboxEmail.toGroup = []
        this.ccGroup = []
        this.toGroup = []
        this.inboxEmail.attachGroup = []
        this.inboxEmail.copyBoxShow = false
        this.inboxEmail.toBoxShow = false
        this.$nextTick(function () {
          this.chatMsgChange()
        })
      },
      showEmailDetails (mail) {
        this.chatMsgCon.showForward = false
        this.chatMsgCon.showDetailAttach = false
        this.chatMsgCon.currAttachVisible = false
        this.chatMsgCon.forwardGroup = []
        let result = deepClone(mail)
        this.chatMsgCon.emailDetail = result
        this.chatMsgCon.showDetail = true  // 显示邮件详情
        this.chatMsgCon.show = true
        this.chatMsgCon.emailType = result.emailType
      },
      replyAll (mail) { // 全部回复
        this.autoAssociationArray = []
        let currentEmailAddress = this.currEmailSession.to.addr
        let result = deepClone(mail)
        this.chatMsgCon.emailDetail = result
        this.toGroup = []
        this.ccGroup = []
        this.inboxEmail.toGroup = []
        this.inboxEmail.ccGroup = []
        this.toGroup.push(result.from)
        this.inboxEmail.toGroup.push(result.from)
        result.to.forEach((item, index) => {
          if (item.addr !== currentEmailAddress) {
            this.toGroup.push(item)
            this.inboxEmail.toGroup.push(item)
          }
        })
        result.cc.forEach((item, index) => {
          if (item.addr !== currentEmailAddress) {
            this.ccGroup.push(item)
            this.inboxEmail.ccGroup.push(item)
          }
        })
        this.$store.dispatch('getMemoryRecipient', {}).then((res) => {
          if (res.success && res.data.length) {
            this.autoAssociationArray = deepClone(res.data)
          }
          this.inboxEmail.copyBoxShow = true
          this.inboxEmail.toBoxShow = true
          this.$nextTick(function () {
            this.chatMsgChange()
          })
        })
      },
      changeDetailAttachStatus () {
        this.chatMsgCon.showDetailAttach = !this.chatMsgCon.showDetailAttach
      },
      showChatAttach (attach, index) {
        if (!this.chatMsgCon.currAttachment || this.chatMsgCon.currAttachment === index) {
          this.chatMsgCon.currAttachVisible = !this.chatMsgCon.currAttachVisible
        }
        if (this.chatMsgCon.currAttachment !== index) {
          this.chatMsgCon.currAttachVisible = true
        }
        this.chatMsgCon.chatAttach = attach
        this.chatMsgCon.currAttachment = index
      },
      ccInputChange (data) {
        this.inboxEmail.ccGroup = data
        this.ccGroup = data
        this.$nextTick(function () {
          this.chatMsgChange()
        })
      },
      toInputChange (data) {
        this.inboxEmail.toGroup = data
        this.toGroup = data
        this.$nextTick(function () {
          this.chatMsgChange()
        })
      },
      initDataChange () {
        this.$nextTick(function () {
          this.chatMsgChange()
        })
      },
      attachInputChange (data) {
        this.inboxEmail.attachGroup = data
        this.$nextTick(function () {
          this.chatMsgChange()
        })
      },
      cancelCcInput () {
        this.ccGroup = []
        this.inboxEmail.ccGroup = []
        this.inboxEmail.copyBoxShow = false
        this.$nextTick(function () {
          this.chatMsgChange()
        })
      },
      cancelToInput () {
        this.toGroup = []
        this.inboxEmail.toGroup = []
        this.inboxEmail.toBoxShow = false
        this.$nextTick(function () {
          this.chatMsgChange()
        })
      },
      initUploadEmailFile () {
        let self = this
        let fileAdded = function (up, files) {
          console.log('fileAdd')
        }
        let beforeUpload = function (up, file) {
          console.log('beforeUpload1')
        }
        let uploadProgress = function (up, file) {
          self.attachUpPro.flag = true
          self.attachUpPro.progress = file.percent
          self.chatMsgChange()
          if (document.getElementsByClassName('verification_box_attach').length) {
            document.getElementsByClassName('verification_box_attach')[0].scrollTop = document.getElementsByClassName('verification_ul')[0].scrollHeight
          }
        }
        let uploadComplete = function () {
          console.log('uploadComplete1')
        }
        let fileUploaded = function (up, file, info) {
          let domain = up.getOption('domain')
          let res = JSON.parse(info||'{}')
          let sourceLink = domain + (self.$store.state.isUseQiniu ? res.key : file.fileKey) // 获取上传成功后的文件的Url
          let trueName = file.name
          self.inboxEmail.attachGroup.push({name: trueName, url: sourceLink})
          self.attachUpPro.flag = false
          self.$nextTick(function () {
            self.chatMsgChange()
            if (document.getElementsByClassName('verification_box_attach').length) {
              document.getElementsByClassName('verification_box_attach')[0].scrollTop = document.getElementsByClassName('verification_ul')[0].scrollHeight
            }
          })
        }
        let error = function (up, err, errTip) {
          self.$message.error(errTip)
        }
        let key = function (up, file) {
          let today = new Date()
          let time = today.getTime()
          let fileName = file.name
          let key = 'email/' + time + '/' + uuid.v1() + '/' + fileName
          return key
        }
        this.m7uploaders.push(
          uploadTo7moorEmailDomain(this.sessionUserId, 'uploadEmailFile', {}, fileAdded, beforeUpload, uploadProgress, uploadComplete, fileUploaded, error, key, this.attachmentMaxSize)
        )
      },
      initUploadImageFile () {
        let self = this
        let fileAdded = function (up, files) {
          console.log('fileAdd')
        }
        let beforeUpload = function (up, file) {
          console.log('beforeUpload1')
        }
        let uploadProgress = function (up, file) {
          console.log('uploadProgress1')
        }
        let uploadComplete = function () {
          console.log('uploadComplete1')
        }
        let fileUploaded = function (up, file, info) {
          let domain = up.getOption('domain')
          let res = JSON.parse(info||'{}')
          let sourceLink = domain + (self.$store.state.isUseQiniu ? res.key : file.fileKey) // 获取上传成功后的文件的Url
          // self.editor.txt.append('<img src="' + sourceLink + '" alt="">')
          // 改为图片在光标出插入
          self.editor.cmd.do('insertHtml', filterXSS('<img src="' + sourceLink + '" style="max-width:100%;"/>'))
        }
        let error = function (up, err, errTip) {
          self.$message.error(errTip)
        }
        let key = function (up, file) {
          let today = new Date()
          let time = today.getTime()
          let fileName = file.name
          let key = 'email/' + time + '/' + uuid.v1() + '/' + fileName
          return key
        }
        let filters = {
          mime_types: [
            {title: 'Image files', extensions: 'jpg,jpeg,gif,png,bmp'}
          ]
        }
        this.m7uploaders.push(
          uploadTo7moorEmailDomain(this.sessionUserId, 'w-e-img-icon', filters, fileAdded, beforeUpload, uploadProgress, uploadComplete, fileUploaded, error, key)
        )
      },
      // 分类星标,转接座席,完成会话
      initCategoryData () {
//        let categoryList = this.$store.state.session.dicMap.mailCategorys || []
        let categoryList = this.$getCache('mailCategorys') || []
        let filterResult = categoryList.filter((category) => {
          return category.relateMailAddr === this.currEmailSession.to.addr
        })
        filterResult.unshift({categoryName: this.$t('email.uncategorized'), categoryId: 'uncategorized'})
        this.chatHead.mailCategories = filterResult
      },
      selectCategory (selectCategory) {
        let data = {
          mailSessionId: this.currEmailSession._id,
          categoryId: selectCategory._id || selectCategory.categoryId,
          categoryName: selectCategory.categoryName
        }
        defineEmailCategory(this.$store, data).then((res) => {
          this.chatHead.popover3Visible = false
        })
      },
      showFinishPopup () {
        getChannelDic(this.$store).then((res) => {
          let finishTypeOne = []
          res.forEach((item) => {
            if (item.type === 'email') {
              finishTypeOne = item.options || []
            }
          })
          if (finishTypeOne.length === 0) {
            this.$message.error(this.$t('email.isNullByFinishKey'))
            return
          }
          let two = false
          let three = false
          this.chatHead.endSessionLength = 1
          finishTypeOne.forEach((item) => {
            if (!item.options) {
              item.options = []
            } else if (item.options.length) {
              two = true
            }
            item.options.forEach((secondItem) => {
              if (!secondItem.options) {
                secondItem.options = []
              } else if (secondItem.options.length) {
                three = true
              }
            })
          })
          if (two) {
            this.chatHead.endSessionLength = 2
            if (three) {
              this.chatHead.endSessionLength = 3
            }
          }
          this.chatHead.endOptionsUl = finishTypeOne
          this.chatHead.majorstwo = []
          this.chatHead.majorsthree = []
          this.chatHead.endSessionActive = []
          this.chatHead.dialogTableVisible = true
          this.chatHead.isActiveOne = ''
        })
      },
      endSessionFun (flag) {
        if (flag) {
          if (this.chatHead.endSessionFlag === false) {
            this.$message.error(this.$t('public.chooseEndSession'))
            return
          } else {
            let arr = this.chatHead.endSessionActive
            let actName = ''
            let finishKey = ''
            if (arr.length > 2) {
              let one = arr[0]
              let two = arr[1]
              let three = arr[2]
              actName = this.chatHead.endOptionsUl[one].options[two].options[three].name
              finishKey = this.chatHead.endOptionsUl[one].options[two].options[three].key
            } else if (arr.length === 2) {
              let one = arr[0]
              let two = arr[1]
              actName = this.chatHead.endOptionsUl[one].options[two].name
              finishKey = this.chatHead.endOptionsUl[one].options[two].key
            } else {
              let one = arr[0]
              actName = this.chatHead.endOptionsUl[one].name
              finishKey = this.chatHead.endOptionsUl[one].key
            }
            let data = {
              _id: this.currEmailSession._id,
              finishReason: actName,
              finishKey: finishKey
            }
            finishSession(this.$store, data).then(() => {
              this.$router.replace({path: '/index/email'})
              this.$store.commit('BLANK', this.tabType)
            })
            this.chatHead.endSessionActive = []
            this.chatHead.endSessionFlag = false
            this.chatHead.dialogTableVisible = false
          }
        } else {
          this.chatHead.endSessionFlag = false
          this.chatHead.dialogTableVisible = false
        }
      },
      changeEndSessionFlag (value) {
        this.chatHead.endSessionFlag = value
      },
      initMarkData () {
        if (!isEmpty(this.currEmailSession.mailMarks)) {
          this.chatHead.starStateChecked = true
        }
      },
      switchReadState (checked) {
        this.chatHead.popover2Visible = false
        let data = {
          sessionId: this.currEmailSession._id,
          readMark: checked ? 'unread' : 'read'
        }
        doEmailMark(this.$store, data).then(() => {
          this.chatHead.readStateChecked = checked
        })
      },
      switchStarState (checked) {
        this.chatHead.popover2Visible = false
        let data = {
          sessionId: this.currEmailSession._id,
          starMark: checked ? 'mark' : 'unmark'
        }
        doEmailMark(this.$store, data).then(() => {
          this.chatHead.starStateChecked = checked
        })
      },
      showRedirectPopup () {
        this.popoLoading = true
        this.popover1Search = ''
        this.$store.dispatch('getEmailOnlineAgent', {toPeer: this.currEmailSession.toPeer}).then((res) => {
          this.chatHead.onlineAgents = deepClone(res)
          this.openPop1.index = -1
          this.openPop1.isOn = false
          this.pop1Clone = deepClone(res)
          this.popoLoading = false
        })
      },
      transferAgent (toUser, toUserName) {
        let data = {
          _id: this.currEmailSession._id,
          toUser: toUser,
          toUserName: toUserName,
          fromEmail: this.currEmailSession.from.addr,
          cust_status: this.$store.state.email.current.email_todo.currentCustomer.status || ''
        }
        let self = this
        redirectMailSession(this.$store, data).then((success) => {
          this.chatHead.popover1Visible = false
          if (success) {
            self.$router.replace({path: '/index/email'})
          }
        })
      },

      // 快捷回复相关
      removeQuickReplyItem (item) {
        var index = this.editCustomQuickReply.rdata.indexOf(item)
        this.editCustomQuickReply.rdata.splice(index, 1)
      },
      addQuickReplyItem () {
        this.editCustomQuickReply.rdata.push({value: ''})
        this.$nextTick(function () {
          if (document.getElementsByClassName('quick_replay_box').length) {
            document.getElementsByClassName('quick_replay_box')[0].scrollTop = document.getElementsByClassName('quickreplay_box')[0].scrollHeight
          }
        })
      },
      showQuickReplyEditInput () {
        this.editCustomQuickReply = deepClone(this.customQuickReply)
        this.oldCustomQuickReply = deepClone(this.customQuickReply)
        this.custQuickReplyEditIsShow = false
        this.$nextTick(function () {
          if (document.getElementsByClassName('quick_replay_box').length) {
            document.getElementsByClassName('quick_replay_box')[0].scrollTop = document.getElementsByClassName('quickreplay_box')[0].scrollHeight
          }
        })
      },
      custQuickReplySubmit (flag) {
        let cloneData = deepClone(this.editCustomQuickReply) // 自定义快捷回复新设置数据克隆（经过数据验证之后获取不到新设置的数据）
        if (this.$refs.editCustomQuickReply.fields.length) {
          this.$refs.editCustomQuickReply.validate((valid) => {
            if (valid) {
              let vuexData = {}
              if (flag) {
                let arr = []
                this.editCustomQuickReply.rdata.forEach((item) => {
                  arr.push(item.value)
                })
                let data = {
                  quickreplys: arr,
                  moduleType: 'email'
                }
                this.$store.dispatch('saveQuickReplyForEmail', data).then((res) => {
                  if (res.success) {
                    vuexData = cloneData
                    this.$store.commit(types.SET_CUST_QUICK_REPLY, vuexData)
                    this.custQuickReplyEditIsShow = true
                  }
                })
              } else {
                vuexData = deepClone(this.oldCustomQuickReply)
                this.$store.commit(types.SET_CUST_QUICK_REPLY, vuexData)
                this.custQuickReplyEditIsShow = true
              }
            }
          })
        } else {
          if (flag) {
            let arr = []
            let data = {
              quickreplys: arr,
              moduleType: 'email'
            }
            this.$store.dispatch('saveQuickReplyForEmail', data)
            this.$store.commit(types.SET_CUST_QUICK_REPLY, cloneData)
          }
          this.custQuickReplyEditIsShow = true
        }
      },
      quickSendMsg (data) {
        this.editor.txt.html(filterXSS(data))
        this.replyEmailInbox()
      },
      quickCopyMsg (data) {
        let str = this.editor.txt.html()
        this.editor.txt.html(filterXSS(str + data))
      },
      itemToggle (index) {
        if (index === this.open.index) {
          this.open.isOn = !this.open.isOn
        } else {
          this.open.index = index
          this.open.isOn = true
        }
        if (!this.sysQuickReply[index].children) {
          let data = {
            id: this.sysQuickReply[index]._id,
            moduleType: 'email',
            index: index
          }
          this.$store.dispatch('queryEmailTagsById', data)
        }
      },
      editRemark (event) {
        if (this.remarkClone !== event.target.value) {
//          this.currEmailSession.remark = event.target.value
          let data = {
            _id: this.currEmailSession._id,
            remark: event.target.value
          }
          this.$store.dispatch('saveRemark', data).then(() => {
            this.remarkClone = event.target.value
          })
        }
      },
      tabChange (tab) {
        if (tab.name === 'quickreply') {
          if (!this.sysQuickReply.length) {
            doQuerySysQuickReplyList(this.$store, {'moduleType': 'email'})
          }
          if (!this.customQuickReply.rdata) {
            doQueryCustomQuickReplyList(this.$store, {'moduleType': 'email'})
          }
        }
      },

      // 工具类
      getChatShortTime (item) {
        let agentInfo = ''
        if (item.agent) {
          if (this.sessionUserId === item.agent) {
            agentInfo = this.$t('email.me')
          } else {
            agentInfo = getCache('agents', item.agent).displayName
          }
        }
        return item.createTime.substring(5, 19) + ' ' + agentInfo

//        return getDateTimeByStr(time, 'time')
      },
      getTimeLength (lastEmailTimestamp, createTimeStamp) {
        return formatTimestamp(lastEmailTimestamp - createTimeStamp)
      },
      changeScroll () {
        this.$nextTick(function () {
          if (this.$route.path.split('/')[3] === 'email_todo' && document.getElementsByClassName('email_chat_msg').length) {
            document.getElementsByClassName('email_chat_msg')[0].scrollTop = document.getElementsByClassName('email_msg_inner')[0].scrollHeight
          }
        })
      },
      chatMsgChange () { // 当页面高度改时重新计算邮件内容窗口的高度
        let obj = document.getElementsByClassName('attach_and_copy_box')
        let obj1 = document.getElementsByClassName('chatMsgCon')
        let editor = document.getElementById('email_editor_content')
        let addHeight = obj[0].offsetHeight + editor.clientHeight - 60
        if (obj.length) {
          obj1[0].style.height = '-webkit-calc(100vh - 329px - ' + addHeight + 'px)'
        } else {
          obj1[0].style.height = '-webkit-calc(100vh - 329px)'
        }
      },
      changeCopyBoxShow (flag) {
        if (flag) {
          this.inboxEmail.copyBoxShow = true
        }
//        if (flag) {
//          this.inboxEmail.copyBoxShow = true
//        } else {
//          this.inboxEmail.copyBoxShow = false
//        }
        this.$nextTick(function () {
          this.chatMsgChange()
        })
      },
      im_icon (chatMsg) {
        let data = ''
        if (chatMsg.agent) {
          let agentInfo = getCache('agents', chatMsg.agent)
          if (agentInfo.im_icon) {
            data = agentInfo.im_icon + '?imageView2/1/w/50/h/50'
          }
        }
        return data
      },
      initEditor () {
        this.editor = new Editor('#email_editor_menu', '#email_editor_content')
        this.editor.config.menus = [
          'head',  // 标题
          'bold',  // 粗体
          'fontSize',  // 字号
          'fontName',  // 字体
          'italic',  // 斜体
          'underline',  // 下划线
          'strikeThrough',  // 删除线
          'foreColor',  // 文字颜色
          'backColor',  // 背景颜色
          'link',  // 插入链接
          'list',  // 列表
          'justify',  // 对齐方式
          'quote',  // 引用
          // 'emoticon',  // 表情
          'table',  // 表格
          // 'code',  // 插入代码
          'undo',  // 撤销
          'redo'  // 重复
        ]
        this.editor.config.pasteTextHandle = filterXSS
        this.editor.config.fontNames = [ '微软雅黑', '宋体', '新宋体', '仿宋', '楷体', '黑体', 'Arial', 'Arial Black', 'Times New Roman', 'Courier New', 'Tahoma', 'Verdana' ]
//        this.editor.config.onchange = (html) => {
          // html 即变化之后的内容
//          this.mailSignatureClone.content = this.editor.txt.html()
//        }
        this.editor.config.zIndex = 100
        this.editor.config.uploadImgShowBase64 = true // 剪切图片到编辑器
        let lang = window.langJson || {}
        let editLang = lang.wangeditor
        this.editor.config.lang = editLang
        this.editor.create()
//        添加图片上传组件
        let div = document.createElement('div')
        div.className = 'w-e-menu'
        div.style.cssText = 'z-index:101;'
        let span = document.createElement('i')
        span.className = 'w-e-icon-image'
        span.id = 'w-e-img-icon'
        div.appendChild(span)
//        添加邮件满意度评价按钮
        if (document.getElementsByClassName('w-e-toolbar')[0]) {
          document.getElementsByClassName('w-e-toolbar')[0].appendChild(div)
        }
//        初始化图片上传组件
        this.initUploadImageFile()
      },
//      发送满意度评价
      pushEmailCSRInfo () {
        let data = {
          sessionId: this.currEmailSession._id,
          carryAgentInfo: this.inboxEmail.carryAgentInfo
        }
        this.$store.dispatch('pushEmailCSRInfo', data).then((res) => {
          if (res.success) {
            this.$message.success(m7Language('email.sendEvaluation'))
          } else {
            this.$message.error(res.message)
          }
        })
      },
      investigateShow (flag) {
        if (flag) {
          this.investigate = true
        } else {
          this.investigate = false
        }
      },
      resizeContainerBar (resizeBar) { // 拖动改变邮件编辑器的大小
        let self = this
        resizeBar.onmousedown = function (e) {
          self.resizeParams.flag = true
          document.querySelectorAll('body')[0].style.userSelect = 'none'
          let editor = document.getElementById('email_editor_content')
          let container = document.getElementsByClassName('chatMsgCon')
          let obj = document.getElementsByClassName('attach_and_copy_box')
          let emailBox = document.getElementsByClassName('chat_msg_box')[0]
          let startY = e.clientY
          resizeBar.top = resizeBar.offsetTop
          document.onmousemove = function (event) {
            if (self.resizeParams.flag) {
              var endY = event.clientY
              var moveLen = resizeBar.top + (endY - startY) + obj[0].offsetHeight
              if (moveLen < 250) moveLen = 250
              let editHight = emailBox.clientHeight - moveLen - 65 - 6
              if (editHight >= 60) {
                resizeBar.style.top = moveLen
                editor.style.height = editHight >= 60 ? editHight + 'px' : '60px'
                let addHeight = obj[0].offsetHeight + (editHight - 60)
                container[0].style.height = '-webkit-calc(100vh - 329px - ' + addHeight + 'px)'
              } else {
                editor.style.height = '60px'
                container[0].style.height = '-webkit-calc(100vh - 329px - ' + obj[0].offsetHeight + 'px)'
              }
            }
          }
          document.onmouseup = function () {
            console.log(container[0].style.height)
            window.sessionStorage.setItem('containerHeight', container[0].style.height)
            window.sessionStorage.setItem('editHight', editor.style.height)
            document.querySelectorAll('body')[0].style.userSelect = 'text'
            document.onmousemove = null
            document.onmouseup = null
            self.resizeParams.flag = false
          }
        }
      }
    },
    beforeMount () {
      this.initEmailRelate()
      this.fetchData()
    },
    beforeDestroy () {
      this.m7uploaders.forEach(uploader => {
        uploader &&
        uploader.destroy &&
        uploader.destroy()
      })
    },
    mounted () {
      if (this.tabType === 'email_todo') {
        this.initEditor()
        this.initUploadEmailFile()
        this.changeScroll()
        this.$store.dispatch('emailConfigEnter', {}).then((res) => {
          let email = this.currEmailSession.to.addr
          let data = false
          if (res.data.emailRelate.length) {
            res.data.emailRelate.forEach((item) => {
              if (item.email === email) {
                data = item.seatSendEvaluation
              }
            })
          }
          let satisfaction = document.createElement('div')
          satisfaction.className = 'w-e-menu emailCSR'
          satisfaction.style.cssText = 'z-index:101;'
          let icon = document.createElement('i')
          icon.className = 'iconfont icon-pingjia'
          satisfaction.appendChild(icon)
          satisfaction.addEventListener('click', this.pushEmailCSRInfo)
          if (document.getElementsByClassName('w-e-toolbar')[0] && data) {
            document.getElementsByClassName('w-e-toolbar')[0].appendChild(satisfaction)
          }
        })
        let resizeBar = document.getElementById('resizeBar') // 改变邮件输入框大小的长条
        let editor = document.getElementById('email_editor_content')
        let container = document.getElementsByClassName('chatMsgCon')[0]
        this.resizeContainerBar(resizeBar)
        if (window.sessionStorage.getItem('containerHeight')) { // 设置改变后的邮件文本框的高度
          editor.style.height = window.sessionStorage.getItem('editHight')
          container.style.height = '-webkit-calc(100vh - 329px - ' + (parseInt(window.sessionStorage.getItem('editHight')) - 60) + 'px)'
        }
      }
    }
  }
  function replyEmailInboxDispatch (store, data) {
    return store.dispatch('replyInbox', data)
  }
  function getChannelDic (store) {
    return store.dispatch('getCache', {type: 'channelDic'})
  }
  function finishSession (store, data) {
    return store.dispatch('finishEmailSession', data)
  }
  function defineEmailCategory (store, data) {
    return store.dispatch('defineMailCategory', data)
  }
  function doEmailMark (store, data) {
    return store.dispatch('doMailMark', data)
  }
  function redirectMailSession (store, data) {
    return store.dispatch('redirectEmailSession', data)
  }
  function doQuerySysQuickReplyList (store, data) {
    return store.dispatch('queryEmailAllTagsForEmail', data)
  }
  function doQueryCustomQuickReplyList (store, data) {
    return store.dispatch('getQuickReplyListForEmail', data)
  }
</script>
<style lang="stylus" scoped>
  @import "../../../assets/common.styl"
  .email_send_box
    border-top 1px solid #e6e6e6
  .chat_info_li
    line-height 16px
    margin-bottom 4px
  overflow-y auto
  .chat_info_box .chat_info_label
    display inline-block
  .chat_msg_box
    border-right 1px solid #d3d3d3
  .active
    background $c-card
  .chat_top
    position relative
    height 35px
    overflow hidden
    box-sizing border-box
    border-bottom 1px solid $c-border1
  .chat_top_head
    float left
    max-width calc(100% - 248px)
    box-sizing border-box
    position relative
    line-height 40px
  .chat_transfer
    float right
    margin -5px 10px 0 0
    height 35px
    .iconfont
      cursor pointer
      font-size 18px
      margin 0 10px
      line-height 30px
      color $cf-gray5
    .email_mark
      color $cf-gray3
      font-size 12px
      margin 0 10px 0 0
      .el-icon-arrow-down
        color $cf-gray5
      span
        max-width 90px
        overflow hidden
        white-space nowrap
        text-overflow ellipsis
        display inline-block
  .avatar
    position absolute
    left 0
  .title
    margin-left 10px
    .chat_title_time
      color $cf-gray4
  .tableVisibleBtn
    display inline-block
  .tableVisibleBtnBox
    clear both
    text-align center
    padding-top 10px
  .dic_item_desc_radio
    position absolute
    display inline-block
    width 100%
    height 100%
    opacity 0
    cursor pointer
  .email_chat_msg
    padding 25px 14px 0
    box-sizing border-box
    overflow auto
  .chat_item
    position relative
    width 70%
    padding-left 34px
  .chat_user_info
    position absolute
    left 0
    top 12px
    .chat_time
      position absolute
      left 65px
      top -30px
      white-space nowrap
  .chat_user_img
    border-radius 50%
    width 40px
    height 40px
    overflow hidden
    background url("../../public-modules/contact-summary/img/agent.png") no-repeat 50% 50%
    background-size 40px auto
    img
      width 100%
      background $cf-white
  .chat_time
    color #9A9A9A
    text-align center
    line-height 16px
  .chat_item.in
    .chat_content
      p
        color $cf-gray0
  .chat_item.out
    .chat_content
      p
        color $cf-gray0
  .chat_content
    max-width 90%
    padding 10px 10px 4px
    position relative
    margin-left 14px
    border-radius 18px
    background #cce5ff
    .send_status
      position absolute
      width 20px
      height 20px
      border-radius 50%
      left -30px
      top 50%
      margin-top -13px
    .send_status.process
      background url('../webchat/img/webchat_send.gif') no-repeat
      background-size 20px 20px
    .send_status.failure
      color $c-pink
      text-align center
      line-height 20px
      font-size 20px
    .send_status.success
      color $cf-white
      text-align center
      line-height 20px
      font-size 14px
      background #1aba9d
  .chat_item
    .chat_content
      p
        overflow hidden
        max-height 54px
        line-height 18px
        word-break break-all
  .chat_content_arrow
    border-top 6px solid transparent
    border-bottom 6px solid transparent
    border-right 6px solid #cce5ff
    content ' '
    position absolute
    width 0
    height 0
    left -9px
    top 10px
    border-radius 1px
    transform rotate(95deg)
    border 5px solid #cce5ff
    border-color #cce5ff transparent transparent #cce5ff
  .chat_user_info_out
    position absolute
    right 0
    top -2px
    .chat_time
      position absolute
      white-space nowrap
      right 75px
      top -16px
  .chat_item.out
    padding 0 50px 0 0
    float right
    .chat_user_img
      border-radius 50%
      width 40px
      height 40px
      float right
    .chat_content
      float right
      background #F2F2F2
      margin 0 14px 0 0
    .email_do_btn
      color $cf-gray0
  .chat_content_arrow_out
    border-left 6px solid #f2f2f2
    border-top 6px solid transparent
    border-bottom 6px solid transparent
    border-right 6px solid #f2f2f2
    content ' '
    position absolute
    width 0
    height 0
    right -9px
    top 10px
    border-radius 1px
    transform rotate(83deg)
    border 5px solid #f2f2f2
    border-color transparent transparent #f2f2f2 #f2f2f2
  .chat_item.system
    text-align center
    width 100%
    padding 0
    .chat_content
      display inline-block
      width 35%
      height 26px
      border-radius: 13px
      text-align center
      display inline-block
      padding 0
      line-height 26px
      background #f2f2f2
  .chat_msg_con
    textarea
      resize none
  .el-form-item
    margin 0
  .replyMsg
    float right
    min-width: 70px
    height: 25px
    line-height: 25px
  .msg_do
    margin-left 0
  .fontSize
    min-width 20px
  .fontSize
    li
      line-height 28px
  .upload
    display inline-block
    width 22px
  .blacklist_con
    resize none
  .other_msg
    .iconfont
      font-size 18px
      cursor pointer
  .other_msg
    .iconfont:hover
      color $c-main
  .upload
    width 20px
  .email_todo_conbox
    .email_chat_msg
      height calc( 100vh - 329px)
  .email_all_conbox
    .email_chat_msg
      height calc( 100vh - 172px)
  .chat_info
    position relative
    overflow-x hidden
    .chat_info_todo
    .chat_info_all
      margin-top -1px
      box-sizing border-box
      height calc(100vh - 171px)
    .chat_info_all
      padding 0 14px
  .chat_info_li_title,.chat_info_all i
    color $cf-gray3
    font-style normal
  .chat_info_li_con
    float right
  .chat_info_li_remarks
    resize none
    font-size 12px
    box-sizing border-box
    width 100%
    margin-top 6px
    border-color $cf-gray5
    padding 6px
    border-radius 4px
  textarea:focus
    border-color $c-main
  .el-tree
    border none
  .quickreplay_custome_title
    padding 0 0 8px
    font-weight bold
    span
      float right
      font-size 12px
      line-height 20px
      cursor pointer
      margin-right 6px
  .quickreplay_li
    .edit_del
      position absolute
      right 4px
      top 0
  .quickRe
    display none
    color $c-main
    float right
    margin-right 4px
    cursor pointer
  .quickReLi
    width 100%
    position relative
    box-sizing border-box
    padding 2px 0 2px 20px
    color $cf-gray3
    height 22px
  .quickReLi:before
    content '\ '
    background $c-sub
    width 4px
    height 4px
    position absolute
    left 10px
    top 6px
  .quickReBox
    position absolute
    right 0
    top 0
  .quickReLi:hover
    padding-right 40px
    .quickRe
      display inline-block
  .quickreplay_custom
    position relative
  .quickreplay_custom_con
    li
      margin-bottom 4px
      position relative
  .quickreplay_custom_con
    li
      i
        line-height 16px
  .quickreplay_box
    color $cf-gray2
    .quickreplay_sys
      position relative
    .quickBoxTit
      padding 0 0 8px
      font-weight bold
    .tree
      padding-left 10px
      .quickReLi:before
        top 8px
    .el-tree
      .is-leaf
        display none
  .color
    color #1f2d3d
  .popover1
    font-size 12px
    .quickReLi:before
      display none
    .quickReLi
      padding-left 18px
  .transfer_li
    color #989898
    height 16px
    padding 4px 0
    cursor pointer
  .transfer_li:hover
    background $c-card
    .transfer_btn
      display inline-block
  .transfer_btn
    display none
    color $c-main
    cursor pointer
    float right
    margin-right 6px
  .transfer_li_ul .transfer_li
    padding-left 18px
  .msg_li
    min-height 62px
    margin-bottom 30px
  .msg_li.system_li
    height 20px
    min-height 0
    margin 10px 0
  .transfer_li_box
    position relative
    font-size 12px
    margin 4px 0
  .transfer_group_btn
    position absolute
    top 0
    right 0
  .box1:hover
    .transfer_group_btn
      display inline-block
  .box1:hover
    .transfer_li
      background $c-card
  .send_msg_form
    position relative
    textarea
      width 100%
      border none
      box-sizing border-box
      resize none
  .font12
    font-size 12px
  .font14
    font-size 14px
  .font16
    font-size 16px
  .font18
    font-size 18px
  .font20
    font-size 20px
  .suggest
    width 308px
    background $cf-white
    bors(1px,#eee)
  .client_msg
    height 36px
  .chat_info_all
    padding-top 18px
    max-height calc(100vh - 218px + 28px)
    max-height -webkit-calc(100vh - 218px + 28px)
    max-height -moz-calc(100vh - 218px + 28px)
    overflow-y auto
  .transfer_li
    .cata-name
      display inline-block
      width 100%
  .cursor_li
    cursor pointer
    height 22px
    line-height 22px
  .chat_info_title
    color $cf-gray2
    word-break break-all
    font-weight bold
  .chat_info_all
    .chat_info_title
      margin 8px 0 5px
  .email_todo_conbox
    .basic_info
      padding 6px 14px
      max-height calc( 100vh - 207px)
      box-sizing border-box
      overflow auto
      .chat_info_title
        margin-bottom 6px
        max-height 40em
        overflow hidden
  .email_do_btn
    line-height 22px
    margin-top 4px
    color $cf-gray0
    display flex
    align-items center
    justify-content flex-end
    .el-icon-arrow-right
      cursor pointer
      text-align center
      line-height 20px
      height 20px
      width 20px
      font-size 20px
    .attachment_box
      margin-right 8px
      height 20px
      .attachment_btn
        cursor pointer
        font-size 20px
        line-height 20px
        span
          margin-left 5px
          font-size 16px
          line-height 20px
  .email_do_btn_box
    height 24px
  .email_all_content
    max-height calc(100vh - 400px)
    max-height -webkit-calc(100vh - 400px)
    max-height -moz-calc(100vh - 400px)
    overflow-y auto
    padding-top 20px
  .email_title
    font-size 22px
    float left
    width 100%
    color $cf-gray2
    font-weight bold
  .email_details_do
    color $c-main
    position absolute
    right 0
    width 80px
    .iconfont
      cursor pointer
  .email_title_info
    border-bottom 1px solid #cdcdcd
    padding-bottom 10px
  .popover3
    max-height 106px
    overflow-y auto
  .popover2
  .popover3
    font-size 12px
    width 88px
    color $cf-level2
    text-align center
    li
      line-height 26px
    .email_mark_li
      line-height 36px
    li:hover
      background $c-card
      cursor pointer
    .email_unread
      border-bottom 1px solid #e7e7e7
  .mail_pop
    box-sizing border-box
  .cancel_star
    padding-left 24px
  .popover1_input
    background-color $cf-white
    border-radius 4px
    border 1px solid #c0ccda
    color #1f2d3d
    display block
    font-size inherit
    height 36px
    line-height 1
    padding 3px 10px
    width 100%
    box-sizing border-box
  .popover_attachment
    position absolute
    background $cf-white
    width 160px
    border-radius 2px
    border 1px solid #D3DCE6
    padding 10px
    z-index 2000
    font-size 12px
    box-shadow 0 2px 4px 0 rgba(0,0,0,.12), 0 0 6px 0 rgba(0,0,0,.04)
    left -82px
  .forward_btn
    margin-left 12px
  .incidentalAgentInfo
    float right
    margin-right 6px
    line-height 25px
    color #a5a5a5
  .email_dialog
    position relative
    padding-right 90px
    width 100%
    box-sizing border-box
    line-height 22px
  .attachment_box
    position relative
    display inline-block
  .pop_arrow
    color transparent
    top -13px
    left 50%
    margin-right 3px
    border-top-width 0
    border-bottom-color #D3DCE6
    border-width 6px
    position absolute
    display block
    width 0
    height 0
    border-style solid
  .pop_arrow:after
    content " "
    border-width 6px
    position absolute
    display block
    width 0
    height 0
    border-color transparent
    border-style solid
    top 1px
    margin-left -6px
    border-top-width 0
    border-bottom-color $cf-white
  .email_details_attachment
    left -78px
    top 26px
  .all_attachment_box
    .iconfont
      color $c-main
  .all_attachment_box_title
    margin 18px 0
    span
      color $cf-gray3
  .all_attachments_ul
  .attach_and_copy
    float left
    line-height 25px
    .addCopy,.addAttach
      display inline-block
      margin-left 10px
      cursor pointer
      color $cf-gray3
    .addCopy.click,.addAttach.click,.addCopy:hover,.addAttach:hover
      color $c-main
  .attach_and_copy_box
    position relative
    .box_p
      width 100%
      box-sizing border-box
      background #fafafa
      padding 6px 30px 6px 70px
    .copy_box_p
      position relative
      .cancel_copy
        position absolute
        left 10px
        color $c-main
        top 50%
        transform translateY(-50%)
      .icon-guanbi
        font-size: 12px
        position absolute
        cursor pointer
        right 10px
        color $c-main
        top 50%
        transform translateY(-50%)
  .copy_box_p.click
      z-index 2
    .attach_box_p.box_p
      font-size 12px
      padding 6px 12px
    .attach_box_p.click
      z-index 2
    .copy_con_box,.attach_con_box
      width 100%
    .icon-xiazai
      cursor pointer
  .chat_info_li_title
    b.chat_info_li_con
      font-weight normal
  .quickreplay_custom_edit
    .quickReplyCancel
      background $c-sub
      border 1px solid $c-sub
    .quickReplySave
      background $c-main
      border 1px solid $c-main
  .button_box
    margin-top 10px
    text-align center
  .sys_quick_li
    position relative
    color $cf-gray1
    .sys_quick_li_span
      position absolute
      left 0
    .sys_quick_li_title
      display inline-block
      width 100%
      box-sizing border-box
      padding-left 20px
  .footer_box
    padding 4px 8px 0
    background: #fff
    z-index: 100
    box-sizing: border-box
    width: 100%
    min-width: 535px
  .email_title_con,.email_detail_content,.email_category_li,.email_mark_li
    color $cf-gray1
  .email_title_con
    text-overflow ellipsis
    overflow hidden
    white-space nowrap
  .email_details_info_li
    color $cf-gray3
    padding-top 5px
  #email_editor_menu
    border-top 1px solid #d9d9d9
  #email_editor_content
    height 60px
  .email_category_li
    max-width 90px
    overflow hidden
    white-space nowrap
    text-overflow ellipsis
  .color1
    color $c-pink
  .color2
    color $c-main
  .quickReBoxShow
    background #fff
    position absolute
    display inline-block
    width calc(100% - 16px)
    height auto
    left 10px
    padding-left 20px
    padding 2px 0 2px 20px
    top 0
    box-shadow 0 0 6px $cf-gray0
    border-radius 5px
    box-sizing border-box
    color $cf-gray0
    min-height 23px
    margin-bottom 4px
    z-index 2
    .cata-name
      word-break break-all
      white-space normal
      width 80%
      display inline-block
  .quickreplay_custome
    position relative
  .el-dialog
    max-height 300px
  .replyAll
    color $c-main
    margin-right 10px
    cursor pointer
  .investigate_con
    position absolute
    bottom 0
    width 100%
    left -8px
    background $cf-white
    box-shadow 0 0 8px #aaa
    padding 8px
    max-height 58px
    overflow-y scroll
    i
      font-style normal
    b
      font-weight normal
      margin-right 4px
    .investigate_content
      word-break break-all
  .investigate_box
    position relative
  .resizeBar
    height 5px
    background #e6e6e6
    cursor ns-resize
    &:before
      content ''
      display block
      width 5px
      height 1px
      margin  1px auto
      border-bottom 1px solid #999
    &:after
      content ''
      display block
      width 5px
      height 1px
      margin 0 auto
      border-bottom 1px solid #999
</style>
